﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DoubleH.Utility.Configuration;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Drawing.Printing;
using System.Threading;

namespace DoubleH.Utility
{
    public partial class FormPrint : Form
    {
        #region win32api
        [DllImport("winspool.drv")]
        public static extern bool SetDefaultPrinter(String Name); //调用win api将指定名称的打印机设置为默认打印机
        #endregion

        public FormPrint()
        {
            InitializeComponent();

            InitVar();
            InitEvent();
        }

        DoubleH.Utility.Configuration.PrintConfig config = null;
        Int64 cors = -1;
        string[] html = null;
        int htmlIndex = 0;
        string defaultPrinterName = null;

        bool autoPrint = false;//防止打开窗体后就自动打印
        /// <summary>
        /// 打印内容加载后是否自动打印？
        /// </summary>
        public bool AutoPrint
        {
            set { autoPrint = value; }
        }

        public void Init(object corSId, DoubleH.Utility.Configuration.PrintConfig obj, params string[] html)
        {
            this.config = null;
            this.cors = -1;
            this.html = null;
            this.htmlIndex = 0;
            //this.isPrint = false;

            this.html = html;
            this.config = obj;
            if (corSId != null)
                cors = (Int64)corSId;

            Debug.Assert(html != null);
            SetDownAndUpButton();
            webBrowser1.DocumentText = html[htmlIndex];
            this.WindowState = FormWindowState.Normal;
            this.Show();
        }

        /// <summary>
        /// 仅限打印小票调用
        /// </summary>
        /// <param name="corSId"></param>
        /// <param name="obj"></param>
        /// <param name="html"></param>
        public void InitForPos(string html)
        {
            printForPos = true;
            webBrowser1.DocumentText = html;
            this.WindowState = FormWindowState.Normal;
            this.Show();
        }

        bool printForPos = false;
        private void StartPrint(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (printForPos)
                PrintForPos();
            else
                PrintForNormal();
        }

        private void PrintForPos()
        {
            PrintDocument pd = new PrintDocument();
            foreach (PrinterCountConfig p in DoubleHConfig.AppConfig.PrinterCount)
            {
                if (!SetDefaultPrinter(p.PrinterName))
                {
                    MessageWindow.Show(p.PrinterName + "  打印机异常.");
                    return;
                }
                Thread.CurrentThread.Join(500);//稍等下

                for (int i = 0; i < p.PrintCount; i++)
                    webBrowser1.Print();

            }
            SetDefaultPrinter(defaultPrinterName);
            pd.Dispose();
        }

        private void PrintForNormal()
        {
            if (!autoPrint)
                return;

            if (config.IsTaoDa)
                webBrowser1.Document.Body.InnerHtml = webBrowser1.Document.GetElementById("DivTaoDa").InnerHtml;

            webBrowser1.Print();
            if (htmlIndex < html.Length - 1)
            {
                htmlIndex += 1;
                webBrowser1.DocumentText = html[htmlIndex];
            }
            else
                autoPrint = false;
        }

        private void InitVar()
        {
            PrintDocument pd = new PrintDocument();
            defaultPrinterName = pd.DefaultPageSettings.PrinterSettings.PrinterName;
            pd.Dispose();
        }

        private void InitEvent()
        {
            this.Load += (ss, ee) => ThisLoad();
            this.FormClosing += (ss, ee) => ThisClose(ee);
            webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(StartPrint);
        }

        private void ThisLoad()
        {
            this.Visible = false;
        }

        private void ThisClose(FormClosingEventArgs ee)
        {
            ee.Cancel = true;
            this.Hide();
        }

        private void toolStripButtonPrint_Click(object sender, EventArgs e)
        {
            if (html == null)
                return;

            autoPrint = true;
            htmlIndex = 0;
            webBrowser1.DocumentText = html[htmlIndex];
        }

        private void toolStripButtonPrintDialog_Click(object sender, EventArgs e)
        {
            webBrowser1.ShowPrintDialog();
        }

        private void toolStripButtonMail_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(DoubleHConfig.UserConfig.EmailSmtp) || string.IsNullOrEmpty(DoubleHConfig.UserConfig.EmailName) || string.IsNullOrEmpty(DoubleHConfig.UserConfig.EmailPwd))
            {
                MessageWindow.Show("邮件配置错误");
                return;
            }
            WindowEmail we = new WindowEmail();
            we.Init(cors, webBrowser1.DocumentText);
            we.ShowDialog();
        }

        private void toolStripButtonConfig_Click(object sender, EventArgs e)
        {
            PrintConfig cf = new PrintConfig();
            cf.Init(config);
            cf.ShowDialog();
        }

        private void toolStripButtonPrintCurrent_Click(object sender, EventArgs e)
        {
            webBrowser1.Print();
        }

        private void toolStripButtonUp_Click(object sender, EventArgs e)
        {
            if (htmlIndex > 0)
            {
                htmlIndex -= 1;
                webBrowser1.DocumentText = html[htmlIndex];
            }
            SetDownAndUpButton();
        }

        private void toolStripButtonDown_Click(object sender, EventArgs e)
        {
            if (htmlIndex < html.Count())
            {
                htmlIndex += 1;
                webBrowser1.DocumentText = html[htmlIndex];
            }
            SetDownAndUpButton();
        }

        private void SetDownAndUpButton()
        {
            toolStripButtonDown.Enabled = true;
            toolStripButtonUp.Enabled = true;

            int count = html.Length;
            if (count < 2)
            {
                toolStripButtonDown.Enabled = false;
                toolStripButtonUp.Enabled = false;
            }
            else if (htmlIndex == 0)
                toolStripButtonUp.Enabled = false;
            else if (htmlIndex == count - 1)
                toolStripButtonDown.Enabled = false;
        }
    }
}